#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author  : ganuoxun
# @description : 全局参数配置

import configparser
import logging
import os
import sys
from functools import lru_cache

config_file = os.path.join(os.path.dirname(__file__), 'config.ini')


class GlobalConfig:
    if not os.path.exists(config_file):
        raise FileNotFoundError("No such file: %s" % config_file)

    _config = configparser.ConfigParser()
    _config.read(config_file, encoding='utf-8')

    # fastapi 配置
    PORT = int(_config.get('fastapi', 'port'))

    # MongoDB配置
    MONGO_URI = _config.get('mongodb', 'URI')

    # s3 select
    SELECT_NAME = _config.get('select', 'SELECT_NAME')

    # minio
    ACCESS_KEY_ID = _config.get('minio', 'ACCESS_KEY_ID')
    SECRET_ACCESS_KEY = _config.get('minio', 'SECRET_ACCESS_KEY')
    ENDPOINT_URL = _config.get('minio', 'ENDPOINT_URL')
    BUCKET = _config.get('minio', 'BUCKET')

    # s3
    S3_ACCESS_KEY_ID = _config.get('s3', 'S3_ACCESS_KEY_ID')
    S3_SECRET_ACCESS_KEY = _config.get('s3', 'S3_SECRET_ACCESS_KEY')
    S3_SECRET_NAME = _config.get('s3', 'S3_SECRET_NAME')
    S3_REGION_NAME = _config.get('s3', 'S3_REGION_NAME')
    S3_BUCKET = _config.get('s3', 'S3_BUCKET')
    S3_PREFIX = _config.get('s3', 'S3_PREFIX')

    # LOG日志配置
    LOG_PATH = _config.get('log', 'LOG_PATH')
    LOG_WHEN = _config.get('log', 'LOG_WHEN')
    LOG_BACKCOUNT = int(_config.get('log', 'LOG_BACKCOUNT'))

    # spark 日志
    CORN = _config.get("spark", "CORN")
    CORES = _config.get("spark", "CORES")
    DRIVER_MEMORY = _config.get("spark", "DRIVER_MEMORY")


@lru_cache()
def get_configs():
    return GlobalConfig()


configs = get_configs()

LOGGING_CONFIG = {
    "version": 1,
    # 如果设置为 True，则已存在的日志记录器（即已经创建的日志记录器）将被禁用，不会继续传播日志消息。新配置的日志记录器会接管整个日志系统。
    # 如果设置为 False 或 0（默认值），已存在的日志记录器将不被禁用，新配置的日志记录器会与已存在的记录器共存。这意味着，已存在的记录器将继续按照它们原有的配置继续工作，而新配置的记录器也会生效。
    "disable_existing_loggers": False,  # 用于在配置日志系统时控制是否禁用已存在的日志记录器。
    "formatters": {
        "default": {
            "()": "uvicorn.logging.DefaultFormatter",
            "fmt": "%(levelprefix)s - %(asctime)s - %(message)s",
            "use_colors": None
        },
        "access": {
            "()": "uvicorn.logging.AccessFormatter",
            "fmt": '%(levelprefix)s - %(asctime)s - %(client_addr)s - "%(request_line)s" - %(status_code)s'
            # noqa: E501
        }
    },
    "handlers": {
        "default": {
            "formatter": "default",
            "class": "logging.handlers.TimedRotatingFileHandler",
            "filename": configs.LOG_PATH,
            "when": configs.LOG_WHEN,
            "encoding": "utf-8",
            "interval": 1,
            "backupCount": configs.LOG_BACKCOUNT
        },
        "access": {
            "formatter": "access",
            "class": "logging.handlers.TimedRotatingFileHandler",
            "filename": configs.LOG_PATH,
            "when": configs.LOG_WHEN,
            "encoding": "utf-8",
            "interval": 1,
            "backupCount": configs.LOG_BACKCOUNT
        }
    },
    "loggers": {
        "uvicorn": {
            "handlers": ["default"],
            "level": "INFO",
            "propagate": False
        },
        "uvicorn.error": {"level": "INFO"},
        "uvicorn.access": {
            "handlers": ["access"],
            "level": "INFO",
            "propagate": False
        }
    }
}

logger = logging.getLogger("uvicorn")


class LoggerWriter(object):
    def __init__(self):
        self.stdout = sys.stdout
        self.list_message = []

    def write(self, message):
        self.stdout.write(message)
        if '\n' in message:
            self.list_message.append(message)
            msg = "".join(self.list_message)
            if msg.strip():
                logger.log(logging.INFO, msg.strip())
            self.list_message.clear()
        else:
            self.list_message.append(message)

    def flush(self):
        pass


logger_writer = LoggerWriter()
